// pages/evaluate/evaluate.js
const orderService = require('../../../../api/orderService.js')
const commentService = require('../../../../api/commentService.js')
const request = require('../../../../api/request.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // avatarUrl: null,
    avatarUrl: [],
    imageUrls: [],
    labels: [{ id: 0, text: '很新鲜', select: false }, { id: 1, text: '服务好', select: false }, { id: 2, text: '分量足', select: false }, { id: 3, text: '干净', select: false }],
    submit: true,
    unSelect: 'http://xianfengapp.oss-cn-hangzhou.aliyuncs.com/xianfengImages/iconUnevaluate.png',
    selected: 'http://xianfengapp.oss-cn-hangzhou.aliyuncs.com/xianfengImages/iconEvaluate.png',
    submit: false,
    inputText: '',
    goodsList: []
  },
  // 选择星星评价
  choiceStars: function (val) {
    console.log(val)
    const idx = val.currentTarget.dataset.index
    let products = this.data.goodsList
    const num = val.currentTarget.dataset.goodsnum
    if (products[num].score !== idx + 1) {
      products[num].score = parseInt(idx + 1)
    } else {
      // 取消评价
      products[num].score = 0
    }
    console.log(products)
    let tempStatus = true
    products.forEach(item => {
      if (item.score === 0 || item.inputText === '') {
        tempStatus = false
      }
    })
    this.setData({
      goodsList: products,
      submit: tempStatus
    })
  },
  // 处理输入框输入内容
  bindTextAreaInput: function (e) {
    console.log(e)
    const idx = e.currentTarget.dataset.goodsnum
    const products = this.data.goodsList
    products[idx].inputText = e.detail.value
    let tempStatus = true
    products.forEach(item => {
      if (item.score === 0 || item.inputText === '') {
        tempStatus = false
      }
    })
    this.setData({
      goodsList: products,
      submit: tempStatus
    })
  },
  // 处理输入框焦点离开
  bindTextAreaBlur: function (e) {

  },
  // 选择图片 上传图片
  chooseImage: function (val) {
    var that = this;
    const idx = val.currentTarget.dataset.goodsnum
    const products = that.data.goodsList
    wx.chooseImage({
      count: 9, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths
        //启动上传等待中...  
        wx.showToast({
          title: '正在上传...',
          icon: 'loading',
          mask: true,
          duration: 200000
        })
        console.log(tempFilePaths)
        var filePaths = products[idx].imageUrls
        console.log(filePaths)
        tempFilePaths.forEach(ele => {
          wx.uploadFile({
            url: request.BASE_URL + '/dfs/upload', //仅为示例，非真实的接口地址
            filePath: ele,
            name: 'file',
            formData: {
              'user': 'test'
            },
            success: function (res) {
              var data = res.data
              let tempData = JSON.parse(data)
              console.log(tempData)
              let tempItem = {
                width: tempData.data.width,
                height: tempData.data.height,
                url: tempData.data.url,
                fileId: tempData.data.id
              }
              filePaths.push(tempItem)
              products[idx].avatarUrl = filePaths
              products[idx].imageUrls = filePaths
              that.setData({
                //将临时变量赋值给已经在data中定义好的变量
                goodsList: products
              })
              wx.hideToast()
            },
            fail: function (e) {
              console.log(e.message)
            }
          })
        });
      }
    })
  },
  // 删除图片
  deleteImg: function (val) {
    Array.prototype.del = function (index) {
      if (isNaN(index) || index >= this.length) {
        return false;
      }
      for (var i = 0, n = 0; i < this.length; i++) {
        if (this[i] != this[index]) {
          this[n++] = this[i];
        }
      }
      this.length -= 1;
    };
    console.log(val)
    const index = val.currentTarget.dataset.id
    const idx = val.currentTarget.dataset.goodsnum
    const products = this.data.goodsList
    products[idx].avatarUrl.del(index)
    this.setData({
      goodsList: products
    })
  },
  // 点击标签
  clickLabels: function (val) {
    const that = this
    let products = this.data.goodsList
    const id = val.currentTarget.dataset.id
    const num = val.currentTarget.dataset.goodsnum
    products[num].labels.forEach((item, index) => {
      if (item.id === id) {
        if (item.select === false) {
          item = {
            ...item,
            select: true
          }
        } else {
          item = {
            ...item,
            select: false
          }
        }
        products[num].labels[index] = item
        that.setData({
          goodsList: products
        })
      }
    })
  },
  /**
   * 获取评论信息
   */
  getProductComments: function () {
    const that = this
    const products = that.data.goodsList
    let productComments = []
    products.forEach(item => {
      let tempImageUrls = []
      const avatarUrl = item.avatarUrl
      const labels = item.labels
      const inputText = item.inputText
      let tempText = ''
      labels.forEach(item => {
        if (item.select) {
          if (tempText === '') {
            tempText = item.text
          } else {
            tempText = tempText + ',' + item.text
          }
        }
      })
      let tempData = {
        content: inputText,
        orderId: that.data.orderId,
        productId: item.productId,
        star: item.score
      }
      // 有标签
      if (tempText !== '') {
        tempData = {
          ...tempData,
          content: tempText + ';' + tempData.content
        }
      }
      // 有图片
      if (item.avatarUrl.length > 0) {
        tempImageUrls = avatarUrl
        tempData = {
          ...tempData,
          pictures: tempImageUrls
        }
      }
      productComments.push(tempData)

    })
    return productComments
  },
  // 提交评论
  submitComment: function () {
    const that = this
    let postData = that.getProductComments()
    let count = 0
    postData.forEach(item => {
      if (item.star !== 0) {
        count++
      }
    })
    if (count === postData.length) {
      commentService.create(postData).then(res => {
        console.log(res)
        wx.showToast({
          title: '评论成功！',
          icon: 'success',
          duration: 2000
        })
        wx.navigateBack({
          delta: 1
        })
      }).catch(e => {
        console.log(e.message)
        wx.showToast({
          title: e.message,
          icon: 'none',
          duration: 2000
        })
      })
    } else {
      wx.showToast({
        title: '请对商品做出评价~',
        icon: 'none',
        duration: 2000
      })
    }
  },
  // 获取待评价订单详情
  getOrderDetails: function () {
    let orderId = this.options.orderId
    orderService.getDetailsById(orderId).then(res => {
      const labels = this.data.labels
      let products = []
      if (res.products && res.products.length > 0) {
        res.products.forEach(ele => {
          let tempData = {
            ...ele,
            labels: [],
            score: 5,
            avatarUrl: [],
            imageUrls: [],
            inputText: ''
          }
          for (let j = 0; j < labels.length; j++) {
            const item = labels[j];
            tempData.labels[j] = item
          }
          products.push(tempData)
        })
      }
      this.setData({
        goodsList: products,
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu()
    if (options.orderId) {
      this.setData({
        orderId: options.orderId
      })
      this.getOrderDetails()
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})